<template>
  <a-drawer
    title="开票信息填写"
    placement="right"
    :width="width"
    :closable="true"
    :visible="visible"
    :get-container="false"
    :wrap-style="{ position: 'absolute' }"
    :after-visible-change="afterVisibleChange"
    @close="close"
  >
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <div class="box" title="查询区域">
        <a-form :form="form" layout="inline" @keyup.enter.native="searchQuery" style="margin:18px 10px 10px 10px">
          <a-row :gutter="24">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="结算单位" style="margin-bottom: 10px;" required>
                <a-select v-model="queryDate.settlementCompany" allowClear showSearch style="width: 100%"
                          placeholder="请选择结算单位" >
                  <a-select-option v-for="(item, key) in companyData" :key="key" :value="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="客户业务编号" style="margin-bottom: 10px;">
                <a-input v-model="queryDate.customerNumber" placeholder="客户业务编号"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="费用名称" style="margin-bottom: 10px;">
                <a-select v-model="queryDate.costName" allowClear showSearch style="width: 100%"
                          placeholder="请选择费用名称">
                  <a-select-option v-for="(item, key) in feeNameData" :key="key" :value="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="主单号" style="margin-bottom: 10px;">
                <a-input v-model="queryDate.mainOffNumber" placeholder="请输入主单号"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="分单号" style="margin-bottom: 10px;">
                <a-input v-model="queryDate.otherOffNumber" placeholder="请输入分单号"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="费用明细币种" style="margin-bottom: 10px;">
                <j-dict-select-tag type="list" v-model="queryDate.currency"
                                   dictCode="currency"
                                   placeholder="请选择币种" />
              </a-form-item>
            </a-col>
            <a-col :xl="9" :lg="7" :md="8" :sm="24">

              <a-form-item label="业务日期" style="margin-bottom: 10px;">
                <a-form-item
                  :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }"
                >
                  <a-date-picker format="YYYY-MM-DD" style="width: 100%" @change="onChangeStart" />
                </a-form-item>
                <span :style="{ display: 'inline-block', width: '24px', textAlign: 'center' }">-</span>
                <a-form-item :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
                  <a-date-picker format="YYYY-MM-DD" style="width: 100%" @change="onChangeEnd" />
                </a-form-item>
              </a-form-item>
            </a-col>
            <!--          </template>-->
            <a-col :xl="3" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
            </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>
    <a-card size="small" title="开票内容" style="width: 100%">
      <a-row>
        <a-col :span="12">
          <a-row>
            <a-col :span="4">开票备注：</a-col>
            <a-col :span="20">
              <a-input v-model="remark" type="textarea" :rows="6" />
            </a-col>

          </a-row>
        </a-col>
        <a-col :span="12">
          <a-row>
            <a-col :span="4"><span>开票信息：</span>
            </a-col>
            <a-col :span="20">
              <a-cascader style="width: 100%" :show-search="{ filter }" :options="selectfpData"
                          placeholder="请选择结算单位的开票信息"
                          @change="onfpChange" />
              <a-input style="margin-top: 5px" v-model="billInfo" type="textarea" :placeholder="kpxxPlaceHolder"
                       :rows="4" />
            </a-col>
          </a-row>
        </a-col>
      </a-row>
    </a-card>


    <!-- 查询区域-END -->
    <a-spin :spinning="confirmLoading">
      <a-card size="small" title="费用明细" style="width: 100%">
        <j-vxe-table
          ref="receivableTable"
          row-selection
          resizable
          keep-source
          :loading="confirmLoading"
          :height="350"
          :dataSource="receivableList"
          :columns="receiveCol"
          @selectRowChange="handleSelectRowChange"
          :cell-style='cellStyle'
          bordered
        >
        </j-vxe-table>
        <div style="padding: 10px;color: red;font-size: 16px">
          已选择金额：{{ selectedFeeDetails }}
        </div>
      </a-card>
    </a-spin>

    <div style="margin-top: 50px"></div>
    <div
      :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'left',
          zIndex: 999,
        }"
    >

      <a-button @click="scClick(1)" type="primary" v-if="!isedit" icon="arrow-up">
        提交申请
      </a-button>
      <a-button :style="{ marginLeft: '8px' }" icon="save" type="default" @click="scClick(2)">
        保存
      </a-button>
      <span :style="{ marginLeft: '8px' }">实开金额：</span>
      <a-input-number style="width: 150px" v-model="skamount" :precision='2' />
      <span :style="{ marginLeft: '8px' }">汇率：</span>
      <a-input-number style="width: 80px" v-model="rate" :precision='2' @change="changeanount" />
      <span :style="{ marginLeft: '8px' }">应收CNY:{{ amount.toFixed(2) }}</span>

      <a-button :style="{ marginLeft: '8px' }" @click="close" icon="close">
        取消
      </a-button>
    </div>
  </a-drawer>
</template>

<script>
import BillForm from '@/views/jzxtrade/modules/BillForm'
import { getAction } from '@/api/manage'
import JFormContainer from '@/components/jeecg/JFormContainer'

import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { postAction } from '../../api/manage'

export default {

  name: 'ExpenseEntrySh',
  components: {
    JFormContainer,
    BillForm,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes
    }
  },
  props: {},
  data() {
    return {
      selectedFeeDetails: '',//已选择金额明细
      kpxxPlaceHolder: '名称：\n' +
        '地址：\n' +
        '银行名称：\n' +
        '银行地址：\n' +
        '银行账号：\n' +
        'SWIFT CODE：\n' +
        'IBAN：\n' +
        'BSB：\n' +
        'ABA：\n' +
        'SORT CODE：\n' +
        'BLZ：',
      labelCol1: { span: 4 },
      wrapperCol1: { span: 14 },
      queryDate: {
        settlementCompany: '',
        customerNumber: '',
        mainOffNumber: '',
        otherOffNumber: '',
        currency: '',
        costName: '',
        etdStart: '',
        etdEnd: ''

      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      feeNameData: [],
      companyData: [],
      selectfpData: [],
      width: '95%',
      Allfee: 0,
      amount: 0,
      skamount: 0,
      rate: 1,
      suffix: '',
      remark: '',
      billInfo: '',
      visible: true,
      selectedRowKeys: [],
      isdelete: false,
      receivableList: [],
      confirmLoading: false,
      modelId: '',
      record: {},
      receiveCol: [
        {
          title: '费用状态',
          key: 'status',
          type: JVXETypes.normal,
          width: '100px',
          defaultValue: '录入状态'
        },
        {
          title: '费用名称',
          key: 'costName',
          type: JVXETypes.normal,
          width: '100px',
          align: 'center'
        },
        {
          title: '结算单位',
          key: 'settlementCompany',
          type: JVXETypes.normal,
          slotName: 'jsdw',
          width: '260px'
        },
        {
          title: '计费单位',
          key: 'chargingUnit',
          type: JVXETypes.normal,
          width: '180px'
        },

        {
          title: '币种',
          key: 'currency',
          type: JVXETypes.normal,
          width: '180px'
        },

        {
          title: '单价',
          key: 'price',
          type: JVXETypes.normal,
          width: '180px'
        },
        {
          title: '数量',
          key: 'num',
          type: JVXETypes.normal,
          width: '180px'

        },
        {
          title: '汇率',
          key: 'rate',
          type: JVXETypes.normal,
          width: '180px'
        },
        {
          title: '总价',
          key: 'totalPrice',
          type: JVXETypes.normal,
          width: '180px'
        },
        {
          title: '本位币金额',
          key: 'cnyAmount',
          type: JVXETypes.normal,
          width: '180px'
        },
        // {
        //   title: '账单号',
        //   key: 'billNumber',
        //   type: JVXETypes.normal,
        //   width: '200px'
        // },
        {
          title: '发票号',
          key: 'invoiceNumber',
          type: JVXETypes.normal,
          width: '200px'
        },
        {
          title: '备注',
          key: 'remark',
          type: JVXETypes.normal,
          width: '200px'
        }
      ],
      url: {
        save: '/box.ship/shipInfo/cost/add',
        queryById: '/box.ship/shipInfo/cost/queryByShipId',
        deleteurl: '/box.ship/shipInfo/cost/del',
        scurl: '/invoice/apply',
        saveurl: '/invoice/save',
        editurl: '/invoice/edit',
        selecturl: '/invoice/query/costinfo'
      },
      receiveCellEdit: true,
      isedit: false,
      // 选择的行
      selectedRows: [],
      form: this.$form.createForm(this, { name: 'coordinated' }),
    }
  },
  computed: {},
  created() {
    this.initDict()
  },
  beforeCreate() {
    // this.form = this.$form.createForm(this, { name: 'dynamic_form_item' });
    // this.form.getFieldDecorator('boxType', { initialValue: [], preserve: true });

    // this.form.getFieldDecorator('keys', { initialValue: [], preserve: true });
  },
  methods: {
    requestRecord(val) {
      this.record = val
      this.selectlist()
      this.remark = this.record.remark
      this.billInfo = this.record.billInfo
      this.isedit = true
    },

    selectlist() {
      let param = { id: this.record.id }
      getAction(this.url.selecturl, param).then(res => {
        console.log(res)
        if (res.success) {
          this.receivableList = res.result
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
      })
    },
    onChangeStart(time, timestring) {
      this.queryDate.etdStart = timestring
    },
    onChangeEnd(time, timestring) {
      this.queryDate.etdEnd = timestring
    },
    searchQuery() {
      // console.log(this.queryDate)
      // 触发表单验证
     if (!this.queryDate.settlementCompany){
       this.$message.warning('结算单位不能为空')
       return
     }
      this.Allfee = 0
      this.amount = 0
      this.skamount = 0
      this.suffix = ''
      this.rate = 1
      this.$refs.receivableTable.clearSelection()
      this.confirmLoading = true
      getAction('/invoice/query/list', this.queryDate).then(res => {
        if (res.success) {
          // that.$emit('allOk')
          this.receivableList = res.result
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    initDict() {
      let param = { isLock: 0, pageSize: 99999 }
      getAction('/fee/list', param).then(res => {
        console.log(res.result.records)
        let feeData = []
        for (let i = 0; i < res.result.records.length; i++) {
          feeData.push({
            value: res.result.records[i].feeName,
            text: res.result.records[i].feeName
          })
        }
        this.feeNameData = feeData
      })
      getAction('/companydata/list', param).then(res => {
        console.log(res.result.records)
        let companyDataList = []
        let selectfpData = []
        for (let i = 0; i < res.result.records.length; i++) {
          companyDataList.push({
            value: res.result.records[i].companyName,
            text: res.result.records[i].companyName
          })
          selectfpData.push({
            value: res.result.records[i].companyName,
            label: res.result.records[i].companyName,
            children: [
              {
                label: '发票信息1',
                value: res.result.records[i].billingInfoOne
              },
              {
                label: '发票信息2',
                value: res.result.records[i].billingInfoTwo
              },
              {
                label: '发票信息3',
                value: res.result.records[i].billingInfoThree
              }
            ]
          })
        }
        this.companyData = companyDataList
        this.selectfpData = selectfpData
      })
    },
    scClick(val) {
      if (this.selectedRows.length == 0) {
        this.$message.warn('请选择需要申请开票的费用明细')
        return
      }
      if (this.skamount == 0) {
        this.$message.warn('请填写开票金额')
        return
      }
      if (!this.billInfo) {
        this.$message.warn('请填写发票信息')
        return
      }
      let ids = []
      let settlementCompany = ''
      for (let i = 0; i < this.selectedRows.length; i++) {
        if (settlementCompany == '') {
          settlementCompany = this.selectedRows[i].settlementCompany
        }
        if (this.selectedRows[i].settlementCompany != settlementCompany) {
          this.$message.warn('请选择同一结算单位申请开票')
          return
        }
        ids.push(this.selectedRows[i].id)
      }
      let param = {}
      if (this.isedit) {
        param = {
          id: this.record.id,
          ids: ids,
          cnyAmount: this.amount,
          amount: this.amount,
          settlementCompany: this.selectedRows[0].settlementCompany,
          currency: this.selectedRows[0].currency,
          rate: this.rate,
          actualAmount: this.skamount,
          remark: this.remark,
          billInfo: this.billInfo
        }
      } else {
        param = {
          ids: ids,
          cnyAmount: this.amount,
          amount: this.amount,
          settlementCompany: this.selectedRows[0].settlementCompany,
          currency: 'CNY',
          rate: this.rate,
          actualAmount: this.skamount,
          remark: this.remark,
          billInfo: this.billInfo
        }
      }

      this.confirmLoading = true
      let leturl = ''
      console.log('isedit', this.isedit)
      if (this.isedit) {
        leturl = this.url.editurl
      } else {
        if (val == 1) {
          leturl = this.url.scurl
        } else {
          leturl = this.url.saveurl
        }
      }

      postAction(leturl, param).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.close()

        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
      })

    },
    // 当选择的行变化时触发的事件
    handleSelectRowChange(event) {
      this.selectedRows = event.selectedRows
      // let allcny = 0
      let allamount = 0
      // this.Allfee = 0
      this.amount = 0
      this.skamount = 0
      this.suffix = ''
      let selectedCnyAmount = 0
      let selectedUsdAmount = 0
      let selectedOtherAmount = 0
      for (let i = 0; i < this.selectedRows.length; i++) {
        if (this.selectedRows[i].currency != 'CNY') {
          allamount += this.selectedRows[i].totalPrice * this.rate
          if (this.selectedRows[i].currency == 'USD') {
            selectedUsdAmount += this.selectedRows[i].totalPrice
          } else {
            selectedOtherAmount += this.selectedRows[i].totalPrice
          }
        } else {
          allamount += this.selectedRows[i].totalPrice
          selectedCnyAmount += this.selectedRows[i].totalPrice
        }
      }
      // this.Allfee = allcny
      this.amount = allamount
      this.skamount = this.amount
      this.selectedFeeDetails = '应收CNY:' + allamount.toFixed(2)
        + ',其中USD:' + selectedUsdAmount.toFixed(2)
        + ',CNY:' + selectedCnyAmount.toFixed(2)
        + ',其他:' + selectedOtherAmount.toFixed(2)
        + ',开票汇率:' + this.rate.toFixed(4)
      this.remark = this.selectedFeeDetails
      // this.changeanount()

    },

    cellStyle(row) {
      // console.log(row.row);
      if (row.row.scode == 2) {//判断条件，如果想要改变其他行样式，就写那一行的下标
        return `background-color: #fff1cf !important;color: #777777`
      } else {
        return `color: #777777`
      }
    },
    changeanount() {
      let allamount = 0
      let selectedCnyAmount = 0
      let selectedUsdAmount = 0
      let selectedOtherAmount = 0
      for (let i = 0; i < this.selectedRows.length; i++) {
        if (this.selectedRows[i].currency != 'CNY') {
          allamount += this.selectedRows[i].totalPrice * this.rate
          if (this.selectedRows[i].currency == 'USD') {
            selectedUsdAmount += this.selectedRows[i].totalPrice
          } else {
            selectedOtherAmount += this.selectedRows[i].totalPrice
          }
        } else {
          allamount += this.selectedRows[i].totalPrice
          selectedCnyAmount += this.selectedRows[i].totalPrice
        }
      }
      // this.Allfee = allcny
      this.amount = allamount
      this.selectedFeeDetails = '应收CNY:' + allamount.toFixed(2)
        + ',其中USD:' + selectedUsdAmount.toFixed(2)
        + ',CNY:' + selectedCnyAmount.toFixed(2)
        + ',其他:' + selectedOtherAmount.toFixed(2)
        + ',开票汇率:' + this.rate.toFixed(4)
      this.remark = this.selectedFeeDetails
      // this.Allfee = parseFloat(this.amount).toFixed(2)

    },
    afterVisibleChange(val) {
      console.log('expenseVisible', val)
    },
    close() {
      this.$emit('close')
      // this.visible = false
    },
    onfpChange(value, selectedOptions) {
      if (value.length > 1) {
        this.billInfo = value[1]
      }

      console.log(value, selectedOptions)
    },
    filter(inputValue, path) {
      return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
    }
  }
}

</script>
<style scoped>
.box {
  position: relative;
  border: 1px solid #e8e8e8;
}

.box::before {
  content: attr(title);
  position: absolute;
  left: 5%;
  transform: translateX(-50%);
  -webkit-transform: translate(-50%, -50%);
  padding: 0 10px;
  background-color: #fff;
}

/deep/ .ant-card-body {
  padding: 10px;
  zoom: 1;
}
</style>
<style>
#components-layout-demo-basic .ant-layout-sider {
  background: #ffffff;
  color: black;
}

#components-layout-demo-basic .ant-layout-content {
  color: #fff;
}
</style>